﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Secondary_File_System.lib;

namespace Secondary_File_System.Model
{
    class Directory
    {
        public int index { get; set; }
        public int fileCount { get; set; }
        public int[] fileInodeIndex { get; set; }
        public Dictionary<string, Inode> dicInodeCache = new Dictionary<string, Inode>();//Dictionary<fileName, Inode>
        public Directory()
        {
            fileCount = 0;
        }
        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="inode">该文件的Inode</param>
        public void addFile(Inode inode)
        {
            int[] newFileInodeIndex = new int[this.fileCount + 1];
            for (int i = 0; i < this.fileCount; i++)
                newFileInodeIndex[i] = this.fileInodeIndex[i];
            newFileInodeIndex[this.fileCount] = inode.index;
            this.fileInodeIndex = newFileInodeIndex;
            this.fileCount += 1;
            this.dicInodeCache.Add(inode.fileName, inode);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="inode">该文件的Inode</param>
        public void deleteFile(Inode inode)
        {
            int[] newFileInodeIndex = new int[this.fileCount - 1];
            for (int newIndex = 0, oldIndex = 0; newIndex < this.fileCount - 1; newIndex++, oldIndex++)
            {
                if (this.fileInodeIndex[oldIndex] == inode.index)
                {
                    newIndex--;
                    continue;
                }
                newFileInodeIndex[newIndex] = this.fileInodeIndex[oldIndex];
            }
            this.dicInodeCache.Remove(inode.fileName);
            this.fileCount -= 1;
            this.fileInodeIndex = newFileInodeIndex;
        }
        public static Directory readFromStream(ref FileStream fs)
        {
            Directory directory = new Directory();
            directory.index = Utility.readIntFromStream(ref fs);
            directory.fileCount = Utility.readIntFromStream(ref fs);
            int[] InodeIndexBuffer = new int[directory.fileCount];
            for (int i = 0; i < directory.fileCount; i++) InodeIndexBuffer[i] = Utility.readIntFromStream(ref fs);
            directory.fileInodeIndex = InodeIndexBuffer;
            return directory;
        }
        public void save(ref FileStream fs)
        {
            Utility.writeBytesToStream(BitConverter.GetBytes(this.index), ref fs);
            Utility.writeBytesToStream(BitConverter.GetBytes(this.fileCount), ref fs);
            foreach (int InodeIndex in this.fileInodeIndex) Utility.writeBytesToStream(BitConverter.GetBytes(InodeIndex), ref fs);
            fs.Flush();
        }
    }
}
